#!/bin/bash
sync && echo 3>/proc/sys/vm/drop_caches
export https_proxy=http://20.20.20.52:3128

user=pkq
cm_port=18327
db_port=19327
WORKSPACE=/data/ss_env
mkdir -p ${WORKSPACE}
echo ${NODE_NAME}
# path 
install_path=/data/ss_env/install
xml_file=${WORKSPACE}/1p2s.xml
env_path=${WORKSPACE}/ENVFILE
DSS_HOME=${install_path}/dss_home
BENCHMARKSQL_PATH=/usr1/test_ss/benchmarksql/run
install_log=/data/yat_log
openGauss3rdbinarylibs=${WORKSPACE}/openGauss-third_party_binarylibs
#share disk
DATA_LUN=/dev/disk/by-id/scsi-36382028100ed96ac1586d3c5000000f2
XLOG_LUN=/dev/disk/by-id/scsi-36382028100ed96ac1586d3c5000000f3
CM_LUN1=/dev/disk/by-id/scsi-36382028100ed96ac1586d3c5000000f4
CM_LUN2=/dev/disk/by-id/scsi-36382028100ed96ac1586d3c5000000f5
# 定义hostname和IP地址的数组
hostnames=("openGauss151" "openGauss153" "openGauss155")
ips=("20.20.20.151" "20.20.20.153" "20.20.20.155")

function create_xml
{
    # 将hostname数组转换为逗号分隔的字符串，用于nodeNames参数
    IFS=','; nodeNames="${hostnames[*]}"; IFS=$' \t\n'
    # 同样，将IP地址数组转换为逗号分隔的字符串，用于cmServerListenIp1参数和backIp1s参数
    IFS=','; cmServerListenIp1="${ips[*]}"; IFS=$' \t\n'
    IFS=','; backIp1s="${ips[*]}"; IFS=$' \t\n'

    # 动态构建<DEVICE>部分
    device_section=""
    for i in "${!hostnames[@]}"; do
        if [ $i -eq 0 ]; then
            # 第一个DEVICE包含完整的cm相关参数
            device_section+="
            <DEVICE sn=\"${hostnames[$i]}\">
                <PARAM name=\"name\" value=\"${hostnames[$i]}\"/>
                <PARAM name=\"azName\" value=\"AZ1\"/>
                <PARAM name=\"azPriority\" value=\"1\"/>
                <PARAM name=\"backIp1\" value=\"${ips[$i]}\"/>
                <PARAM name=\"sshIp1\" value=\"${ips[$i]}\"/>
                <PARAM name=\"cmDir\" value=\"${install_path}/cm\"/>
                <PARAM name=\"cmsNum\" value=\"1\"/>
                <PARAM name=\"cmServerPortBase\" value=\"${cm_port}\"/>
                <PARAM name=\"cmServerListenIp1\" value=\"$cmServerListenIp1\"/>
                <PARAM name=\"cmServerlevel\" value=\"1\"/>
                <PARAM name=\"cmServerRelation\" value=\"$nodeNames\"/>
                <PARAM name=\"dataNum\" value=\"1\"/>
                <PARAM name=\"dataPortBase\" value=\"${db_port}\"/>
                <PARAM name=\"dataNode1\" value=\"${install_path}/data/dn,${hostnames[$((1-$i))]},${install_path}/data/dn,${hostnames[$((2-$i))]},${install_path}/data/dn\"/>
            </DEVICE>"
        else
            # 其他DEVICE按照提供的格式，仅包含cmDir
            device_section+="
            <DEVICE sn=\"${hostnames[$i]}\">
                <PARAM name=\"name\" value=\"${hostnames[$i]}\"/>
                <PARAM name=\"azName\" value=\"AZ1\"/>
                <PARAM name=\"azPriority\" value=\"1\"/>
                <PARAM name=\"backIp1\" value=\"${ips[$i]}\"/>
                <PARAM name=\"sshIp1\" value=\"${ips[$i]}\"/>
                <PARAM name=\"cmDir\" value=\"${install_path}/cm\"/>
            </DEVICE>"
        fi
    done

# 构建完整的XML内容
xml_content=$(cat <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<ROOT>
    <CLUSTER>
        <PARAM name="clusterName" value="cluster" />
        <PARAM name="nodeNames" value="$nodeNames" />
        <PARAM name="gaussdbAppPath" value="${install_path}/app" />
        <PARAM name="gaussdbLogPath" value="${install_path}/log" />
        <PARAM name="tmpMppdbPath" value="${install_path}/tmp"/>
        <PARAM name="gaussdbToolPath" value="${install_path}/tool" />
        <PARAM name="corePath" value="/home/core"/>
        <PARAM name="backIp1s" value="$backIp1s" />
        <PARAM name="enable_dss" value="on"/>
        <PARAM name="dss_home" value="${install_path}/dss_home"/>
        <PARAM name="dss_vg_info" value="data:${DATA_LUN},log:${XLOG_LUN}"/>
        <PARAM name="votingDiskPath" value="${CM_LUN1}"/>
        <PARAM name="shareDiskDir" value="${CM_LUN2}"/>
        <PARAM name="ss_dss_vg_name" value="data"/>
        <PARAM name="dss_ssl_enable" value="off"/>
    </CLUSTER>
    <DEVICELIST>$device_section
    </DEVICELIST>
</ROOT>
EOF
)
	echo "$xml_content"
}

if [[ -d WORKSPACE ]]; then
    mkdir -p $WORKSPACE
fi

function auto_(){
    expect <<-EOF
        spawn $*
        set timeout -1
        expect {
            "yes/no" { send "yes\n"; exp_continue }
            "denied" { exit 1; }
            "*assword:" { send "SS_dedicated_819\n"; exp_continue }  
            "anger*\n*yes*" { send "yes\n"; exp_continue }
            "Pdb" { interact }
            "password:" { send "openGauss1#2_3$00\n"; exp_continue  }  #hu尼玛的
            "password:" { send "openGauss1#2_3$00\n"; exp_continue  }
            "database:" { send "Huawei@123\n"; exp_continue  }
        }
        #expect eof
EOF
}

all_node_ssh_proc()
{
    for ip in "${ips[@]}"
    do
      echo "Executing on $ip"
      auto_ ssh root@$ip $*
    done
}

pre_un_install()
{
	echo "==============clean env==================="
    rm -rf  $install_log/install.log
    su - ${user}<<EOF
        source ${env_path}
        gs_uninstall --delete-data
EOF
}

clean_env()
{
	all_node_ssh_proc "pkill -9 -u ${user}"
    all_node_ssh_proc rm -rf ${WORKSPACE}
    all_node_ssh_proc rm -rf ${env_path}
    all_node_ssh_proc rm -rf ${xml_file}
    all_node_ssh_proc "su - ${user} -c 'ipcrm -a'" >/dev/null
}

get_tar()
{
    echo "==============get tar==================="
    #最新包
    if [[ ! -d ${install_path}/gauss_pack ]]; then
        mkdir -p ${install_path}/gauss_pack
    fi
    cd ${install_path}
 	echo "get tar"
    wget ${PKG_URL}
    #scp /data/openGauss-All-6.0.0-CentOS7-x86_64.tar.gz ./
    #解压包
    cd ${install_path}/gauss_pack >/dev/null
    rm -rf * >/dev/null
    tar -zxf ../openGauss*.tar.gz
    #灵活包地址，非必要别开启
    #cp /usr1/songshixuan_pkq/* ./ -r
    #tar -zxf openGauss*om.tar.gz    旧包命名方式
    tar -zxf openGauss-OM*.tar.gz    #新包命名方式
    chmod 777 -R ${install_path}/
}

# #预安装
pre_install()
{
	rm -rf $install_log/install.log
	mkdir -p $install_log
    chmod 755 ${install_log}
    #echo 'test' >> $install_log/install.log
    touch $install_log/install.log
    
    chmod -R 777 $install_log/install.log
	echo "$xml_content" > ${xml_file}
	set -e
    echo "==============pre_install==================="
    chmod 777 -R ${install_path}/
    
    echo "修改install权限到777"
    chmod 777 -R ${xml_file}
    chmod 777 -R ${WORKSPACE}
    cd ${install_path}/gauss_pack/script/
    auto_ ./gs_preinstall -U ${user} -G ${user}  --sep-env-file=${env_path} -X ${xml_file} > $install_log/install.log 2>&1
    chmod 777 -R ${xml_file}
    all_node_ssh_proc chmod 777 -R ${install_path}/
    all_node_ssh_proc chmod 777 -R ${WORKSPACE}
}

#安装
om_install()
{
	set -e
    echo "==============install==================="
    all_node_ssh_proc chmod 777 -R ${install_path}
su - ${user}<<EOF
    function auto_(){
        expect <<-EOD
            spawn \$*
            set timeout -1
            expect {
                "yes/no" { send "yes\n"; exp_continue }
                "denied" { exit 1; }
                "*assword:" { send "SS_dedicated_819\n"; exp_continue }
                "anger*\n*yes*" { send "yes\n"; exp_continue }
                "Pdb" { interact }
                "pass phrase for*:" { send "SS_dedicated_819\n"; exp_continue  }
                "passphrase" { send "SS_dedicated_819\n"; exp_continue  }
                "database:" { send "Huawei@123\n"; exp_continue  }
            }
EOD
    }
    source ${env_path}

    echo "开始执行gs-install"
    auto_ gs_install -X ${xml_file} >> $install_log/install.log 2>&1
    #查看集群状态
    cm_ctl query -Cvdip
EOF
}

set_guc()
{
	#set -e
    all_node_ssh_proc sed -i 's/_LOG_LEVEL=7/_LOG_LEVEL=255/g' ${DSS_HOME}/cfg/dss_inst.ini
    sh $install_log/setGuc.sh
}

create_user()
{
	set -e
    su - ${user}<<EOF
        source  ${env_path}
        #创建用户
        echo " =================  create tpcc user    ================="
        gsql -d postgres -p ${db_port} -r -c "create database tpcc;create user tpcc_user with password 'Huawei@123';grant all privileges to tpcc_user;"
        gaussdb -V >> ${install_log}/install.log;cm_ctl query -Cvipd; cm_ctl stop; cm_ctl start;cm_ctl switchover -a
        
        
EOF
}

tpcc_build()
{
	cd /data/benchmarksql-5.0/run
    ./runDatabaseBuild.sh props_yat.pg
}

function main() {
	echo "begin test"
    pre_un_install
    clean_env
	set -e
    get_tar
    create_xml
    echo "pre install"
    pre_install
    echo "om install"
    om_install
    set_guc
    create_user
	sshpass -p 'openGauss1#2_3$00' scp $install_log/install.log root@20.20.20.79:/home/songshixuan/YatShell || true
    tpcc_build
}

main "$@"
